import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Link, useSearchParams, useNavigate } from "react-router-dom";
import FormHead from "@/components/custom-ui/form-head";
import PasswordInput from "@/components/custom-ui/password-input";
import CaptchaInput from "@/components/custom-ui/captcha-input";
import OAuthButtons from "@/components/custom-ui/oauth-buttons";
import { Mail } from "lucide-react";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useLogin } from "@/hooks/use-login";
import { useST } from "@/hooks/use-st";
import { LoginSchema, type LoginFormData } from "@/schemas/login";

export default function Login() {
  const [, setCaptchaId] = useState("");
  const { t } = useTranslation();
  const { login, isLogging } = useLogin();
  const { getSTAndRedirect } = useST();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  // 检查并自动添加service参数
  useEffect(() => {
    const serviceParam = searchParams.get("service");

    // 如果没有service参数，自动添加当前页面的host + "/cas/profile"作为service参数
    if (!serviceParam) {
      const currentHost = window.location.origin;
      const defaultService = `${currentHost}/cas/profile`;
      const newSearchParams = new URLSearchParams(searchParams);
      newSearchParams.set("service", defaultService);

      // 使用replace而不是push，避免在浏览器历史中创建额外的记录
      navigate(`/cas/login?${newSearchParams.toString()}`, { replace: true });
    }
  }, [searchParams, navigate]);

  useEffect(() => {
    const serviceParam = searchParams.get("service");
    // 如果有service参数，则自动获取去获取ST并判断是否跳转
    if (serviceParam) {
      getSTAndRedirect(serviceParam);
    }
  }, [searchParams, getSTAndRedirect]);

  const form = useForm<LoginFormData>({
    resolver: zodResolver(LoginSchema()),
    defaultValues: {
      email: "",
      password: "",
      captcha: "",
      captcha_id: "",
      remember_me: true,
      service: "",
    },
  });

  const onSubmit = (data: LoginFormData) => {
    const serviceParam = searchParams.get("service");
    data.service = serviceParam || "";
    login(data);
  };

  return (
    <div className="flex items-center justify-center py-12">
      <Card className="w-full min-w-xs max-w-md border border-white/20">
        <CardHeader className="text-center">
          <FormHead />
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="space-y-4"
              noValidate
            >
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Email", { defaultValue: "Email" })}
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("Enter email", {
                          defaultValue: "Enter email",
                        })}
                        startIcon={<Mail className="h-4 w-4" />}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Password", { defaultValue: "Password" })}
                    </FormLabel>
                    <FormControl>
                      <PasswordInput
                        placeholder={t("Enter password", {
                          defaultValue: "Enter password",
                        })}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="captcha"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Captcha", { defaultValue: "Captcha" })}
                    </FormLabel>
                    <FormControl>
                      <CaptchaInput
                        placeholder={t("Enter captcha code", {
                          defaultValue: "Enter captcha code",
                        })}
                        onCaptchaIdChange={(captchaId) => {
                          setCaptchaId(captchaId);
                          form.setValue("captcha_id", captchaId);
                        }}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <FormField
                    control={form.control}
                    name="remember_me"
                    render={({ field }) => (
                      <Checkbox
                        id="remember_me"
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    )}
                  />
                  <Label
                    htmlFor="remember_me"
                    className="text-sm font-medium text-card-foreground"
                  >
                    {t("Remember Me", { defaultValue: "Remember Me" })}
                  </Label>
                </div>
                <Link
                  to="/cas/forgot"
                  className="text-sm text-blue-600 hover:underline"
                >
                  {t("Forgot password?", { defaultValue: "Forgot password?" })}
                </Link>
              </div>

              <Button
                className="w-full hover:cursor-pointer"
                size="lg"
                type="submit"
                disabled={isLogging}
              >
                {isLogging
                  ? t("Logging...", { defaultValue: "Logging..." })
                  : t("Sign In", { defaultValue: "Sign In" })}
              </Button>
            </form>
          </Form>

          {/* OAuth 登录按钮 */}
          <OAuthButtons className="mt-6" />

          <div className="text-center space-y-2 mt-4">
            <div className="text-sm">
              <Link
                to="/cas/register"
                className="text-blue-600 hover:underline"
              >
                {t("Don't have an account? Sign up now", {
                  defaultValue: "Don't have an account? Sign up now",
                })}
              </Link>
            </div>
            <div className="text-sm">
              <Link to="/cas" className="text-gray-600 hover:underline">
                {t("Back to Home", { defaultValue: "Back to Home" })}
              </Link>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
